//
//  ShellLuanchTool.m
//  AppShellTool
//
//  Created by IOS01 on 2022/12/2.
//

#import "ShellLuanchTool.h"
#import <UIKit/UIKit.h>
#import "ShellLuanchController.h"
#import <objc/runtime.h>
#import "SocketClient.h"

@interface ShellLuanchTool()

@property(nonatomic, strong) UIViewController *rootViewController;

@property(nonatomic, strong) UIViewController *lauchVc;

@end

@implementation ShellLuanchTool
static ShellLuanchTool *luanchTool;

- (instancetype)init{
    if (self = [super init]) {
        //登录完成后重新检查参数
        __weak typeof(self) tempSelf = self;
        self.AfterLoginBlock = ^{
            [tempSelf checkIsShellLuanch];
        };
    }
    return self;
}

+(ShellLuanchTool *)shareTool{
    static dispatch_once_t onceToken2;
    dispatch_once(&onceToken2, ^{
        luanchTool = [[ShellLuanchTool alloc] init];
    });
    return luanchTool;
}
/// 设置传过来的参数
/// @param url url
-(void)setUrl:(NSString *)url{
    _url = url;
    self.isShellPush = YES;
    [[SocketClient shareClient] connect];
}


/// iOS13 使用UISceneDelegate 设置参数
/// @param set 参数
- (void)sceneHadUrlContext:(NSSet *)set{
    NSString *urlStr = nil;
    if (@available(iOS 13.0, *)) {
        for (UIOpenURLContext *context in set) {
            NSURL *url = context.URL;
            urlStr = url.absoluteString;
        }
    }
    if (urlStr) {
        [[ShellLuanchTool shareTool] setUrl:urlStr];
        [[SocketClient shareClient] connect];
    }
}


/// 是否可以退出app去外壳
- (BOOL)isCanOutApllication{
    return self.isShellPush && [self isTopLuancController];
}


/// 检查是否是外壳启动的页面在最上层
- (BOOL)isTopLuancController{
    if ([self.lauchVc isKindOfClass:UINavigationController.class]) {
        UINavigationController *navi = (UINavigationController *)self.lauchVc;
        return [navi.viewControllers.lastObject isKindOfClass:ShellLuanchController.class];
    }else{
        return [self.lauchVc.navigationController.viewControllers.lastObject isKindOfClass:ShellLuanchController.class];
    }
}

/// 进入后台
- (void)enterBackground{
    self.isShellPush = NO;
}

/// 返回壳
- (void)shellIsBack{
//    如果不是从外壳进来的，则正常退出
    if (!self.isShellPush) {
        if ([self.lauchVc isKindOfClass:UINavigationController.class]) {
            [self.lauchVc dismissViewControllerAnimated:YES completion:nil];
        }else{
            [self.lauchVc.navigationController popViewControllerAnimated:YES];
        }
        return;
    }
    self.isShellPush = NO;
    
    
    UIWindow *window =  [UIApplication sharedApplication].keyWindow;
    [UIView animateWithDuration:0.5f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        NSURL *url = [NSURL URLWithString:@"appShell://?appShell"];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{
                UIApplicationOpenURLOptionsOpenInPlaceKey:@YES,
                                                                   } completionHandler:^(BOOL success) {
                exit(0);
            }];
        }else{
            [[UIApplication sharedApplication] openURL:url];
            exit(0);
        }
    }];
    [[SocketClient shareClient] disConnect];
}


/// 检查是否需要弹出控制器
-(void)checkIsShellLuanch{
    
    if (self.isShellPush) {
        
        if (self.AppHadLoginBlock) {
            //未登录则先让app登录，然后再通过登录完成回调该方法
            if (!self.AppHadLoginBlock()) {
                return;
            }
        }
        [self checkRootController];
        if (self.rootViewController) {
            [self loadLuanchController];
        }
    }
}


/// 获取根控制器
- (void)checkRootController{
    
    BOOL isScene = NO;
    id idScene = nil;
    if (@available(iOS 13.0, *)) {
        UIScene *scene = [UIApplication sharedApplication].openSessions.allObjects.lastObject.scene;
        idScene = scene;
        isScene = scene && scene.delegate;
    }
    if (isScene) {
        
        if (@available(iOS 13.0, *)) {
            UIScene *scene = idScene;
            id delegate = scene.delegate;
            int count = 0;
            objc_property_t *propertyList = class_copyPropertyList([delegate class], &count);
            
            for (unsigned int i = 0; i < count; i++) {
                const char *propertyName = property_getName(propertyList[i]);
                NSString *name = [NSString stringWithUTF8String:propertyName];
                SEL sel = NSSelectorFromString(name);
                if ([delegate respondsToSelector:sel]) {
                    NSObject * b = [delegate performSelector:sel];
                    if ([b isKindOfClass:UIWindow.class]) {
                        self.rootViewController = [b performSelector:@selector(rootViewController)];
                        break;
                    }
                }
            }
        }
        
    }else{
        if ([UIApplication sharedApplication].delegate.window) {
            self.rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
        }
    }
}


/// 弹出控制器
- (void)loadLuanchController{
    
    if (self.rootViewController) {
        
        if ([self.rootViewController isKindOfClass:UINavigationController.class]) {
            UINavigationController *naviVc = (UINavigationController *)self.rootViewController;
            //没有push的时候才push
            if (![naviVc.viewControllers containsObject:self.lauchVc]){
                [naviVc pushViewController:self.lauchVc animated:YES];
            }else{
                ShellLuanchController *shellVc = (ShellLuanchController *)self.lauchVc;
                [shellVc addChildController];
            }
        }else{
            self.lauchVc.modalPresentationStyle = UIModalPresentationFullScreen;
            //已经弹出的话就不在弹出
            if (self.rootViewController.presentedViewController && [self.rootViewController.presentedViewController isKindOfClass:self.lauchVc.class]) {
                
                UINavigationController *naviVc = (UINavigationController *)self.lauchVc;
                ShellLuanchController *shellVc = (ShellLuanchController *)naviVc.viewControllers.firstObject;
                [shellVc addChildController];
                
                return;
            }
            [self.rootViewController presentViewController:self.lauchVc animated:YES completion:^{
                            
            }];
        }
    }
}

- (UIViewController *)lauchVc{
    if (_lauchVc == nil) {
        ShellLuanchController *luanchViewController = [[ShellLuanchController alloc] init];
        
        if ([self.rootViewController isKindOfClass:UINavigationController.class]) {
            _lauchVc = luanchViewController;
        }else{
            UINavigationController *naviVc = [[UINavigationController alloc] initWithRootViewController:luanchViewController];
            _lauchVc = naviVc;
        }
    }
    return _lauchVc;
}


@end
